<template>
  <div class="container">
    <header-search-form
      :searchFormData="searchForm"
      @search="search"
    />
    <lan-table
      size="small"
      :config="dataTable"
      :tableData="tableData"
      @search="search"
    >
      <template #type="scope">
        <el-input v-model="scope.row.type"></el-input>
      </template>
      <template #active="scope">
        <span
          v-if="scope.row.active"
          style="color:#07c160"
        >允许</span>
        <span
          v-else
          style="color:#fa5151"
        >不允许</span>
      </template>
    </lan-table>
    <up-load
      ref="uploadComponent"
      @refresh="search"
      @closeExpand="closeExpand"
    ></up-load>
    <edit
      ref="editComponent"
      @refresh="search"
    ></edit>
    <el-dialog
      width="610px"
      title="参数详情"
      :visible.sync="dialogTableVisible"
    >
      <el-table
        stripe
        :data="showReceiveDeviceTableData"
      >
        <el-table-column
          label="名称"
          prop="key"
        ></el-table-column>
        <el-table-column
          prop="value"
          label="数值"
        ></el-table-column>
      </el-table>
      <div class="receive-device-footer">
        <el-pagination
          background="#fff"
          @size-change="pageSizeChangeHandler"
          @current-change="currentPageChangeHandler"
          :current-page.sync="searchFormDialog.currentPage"
          :page-size.sync="searchFormDialog.pageSize"
          :page-sizes="[5, 10, 20, 50, 100]"
          layout="total,sizes, prev, pager, next, jumper"
          :total="searchFormDialog.totalCount"
          align="right"
        ></el-pagination>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Edit from './edit';
import HeaderSearchForm from './headerSearchForm.vue';
import lanTable from '../../../components/lanTable';
import * as moment from 'moment';
import { SortType, MomentFormat } from '../../../constants/common';
import { Message, MessageBox } from 'element-ui';
import { parseError } from '../../../utils';
import { getDeviceSettingListApi, deleteDeviceSettingApi } from '../../../api/deviceSetting';
import UpLoad from './upload';

export default {
  components: {
    lanTable,
    UpLoad,
    Edit,
    HeaderSearchForm
  },
  data() {
    return {
      dataTable: {
        pageSize: 10,
        totalCount: 0,
        currentPage: 1,
        pageSizes: [5, 10, 20, 50, 100],
        sort: {
          orderBy: 'createdAt',
          sortType: SortType.DESC
        },
        columnList: [
          {
            name: 'index',
            label: '',
            type: 'index'
          },
          {
            name: 'name',
            label: '名称'
          },
          {
            name: 'versionName',
            label: '版本号'
          },
          {
            name: 'productTypeName',
            label: '产品类型'
          },
          {
            name: 'active',
            label: '允许升级',
            type: 'slot'
          },
          {
            label: '产品列表',
            type: 'button',
            scope: true,
            buttons: [
              {
                size: 'small',
                text: '查看',
                icon: 'el-icon-tickets',
                method: row => this.toProductList(row.name, row.id)
              }
            ]
          },
          {
            label: '参数详情',
            type: 'button',
            scope: true,
            buttons: [
              {
                size: 'small',
                text: '查看',
                icon: 'el-icon-tickets',
                method: row => this.showDeviceParameterList(row)
              }
            ]
          },
          {
            name: 'description',
            label: '备注'
          },
          {
            name: 'createdAt',
            label: '创建时间',
            sortable: true
          },
          {
            name: 'updatedAt',
            label: '更新时间'
          },
          {
            label: '产品导入',
            type: 'button',
            scope: true,
            buttons: [
              {
                size: 'small',
                text: '上传文件',
                icon: 'el-icon-document-copy',
                method: row => this.showUpload(row.id)
              }
            ]
          },
          {
            type: 'button',
            label: '操作',
            buttons: [
              {
                type: 'text',
                text: '编辑',
                size: 'small',
                method: row => {
                  this.showEdit(row);
                }
              },
              {
                type: 'text',
                text: '删除',
                size: 'small',
                method: row => {
                  this.remove(row.id, row.name);
                }
              }
            ]
          }
        ]
      },
      searchForm: {
        btnLoading: false,
        name: '',
        productTypeUuid: '',
        active: '',
        description: ''
      },
      searchFormDialog: {
        currentPage: 1,
        pageSize: 10,
        totalCount: 0
      },
      dialogTableVisible: false,
      deviceParameterList: {},
      tableData: [],
      showReceiveDeviceTableData: []
    };
  },
  watch: {
    deviceParameterList: {
      handler(val) {
        this.searchFormDialog.totalCount = val.length;
        this.search();
      }
    }
  },
  created() {
    this.search();
  },
  methods: {
    searchDialog() {
      this.showReceiveDeviceTableData = this.deviceParameterList.slice(
        (this.searchFormDialog.currentPage - 1) * this.searchFormDialog.pageSize,
        this.searchFormDialog.currentPage * this.searchFormDialog.pageSize
      );
    },
    pageSizeChangeHandler() {
      this.currentPage = 1;
      this.searchDialog();
    },
    currentPageChangeHandler() {
      this.searchDialog();
    },
    showEdit(row) {
      this.$refs.editComponent.showDialog(row);
    },
    showDeviceParameterList(data) {
      this.deviceParameterList = Object.entries(data.setting).map(([key, value]) => ({ key, value }));
      this.searchDialog();
      this.$nextTick(() => {
        this.searchFormDialog.totalCount = this.deviceParameterList.length;
        this.searchDialog();
      });
      this.dialogTableVisible = true;
    },

    search() {
      this.searchForm.btnLoading = true;
      getDeviceSettingListApi(
        this.dataTable.currentPage - 1,
        this.dataTable.pageSize,
        this.dataTable.sort.sortType,
        this.dataTable.sort.orderBy,
        this.searchForm.name,
        this.searchForm.productTypeUuid,
        this.searchForm.active,
        this.searchForm.description
      )
        .then(({ total_count, data }) => {
          this.dataTable.totalCount = total_count;
          this.tableData = data.map(deviceSetting => {
            return {
              id: deviceSetting.id,
              name: deviceSetting.name,
              description: deviceSetting.description,
              versionName: deviceSetting.version_name,
              createdAt: moment(deviceSetting.created_at).format(MomentFormat),
              updatedAt: moment(deviceSetting.updated_at).format(MomentFormat),
              setting: deviceSetting.setting,
              productTypeUuid: deviceSetting.product_type_uuid || '',
              productTypeName: deviceSetting.product_type_name || '',
              active: deviceSetting.active
            };
          });
        })
        .catch(error => Message.error(parseError(error)))
        .finally(() => (this.searchForm.btnLoading = false));
    },
    toProductList(name, settingId) {
      const productListRoute = this.$router.resolve({
        name: 'upgradeDevice',
        query: {
          settingName: name,
          settingId: settingId
        }
      });
      window.open(productListRoute.href, '_blank');
    },
    showUpload(deviceSettingId) {
      this.$refs.uploadComponent.showDialog(deviceSettingId);
      this.settingId = deviceSettingId;
    },
    remove(id, name) {
      MessageBox.confirm(`确认删除配置参数${name}吗？`, '删除提示', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        deleteDeviceSettingApi(id)
          .then(() => Message.success('删除报警规则成功'))
          .catch(error => Message.error(parseError(error)))
          .finally(() => this.search());
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  padding: 10px;
}
.receive-device-footer {
  padding-top: 10px;
  margin-right: 10px;
  background-color: #fff;
}
</style>
